/*
 * Copyrignt (c) xuzeshui.com. All Rights Reserved.
 * Author: Xiaobao Zeng<zengxiaobao@skyworth.com>
 * Created Time: 2017-03-24 13:06:13
 * Last Modified: 2017-07-10 10:11:52
 * File Name: mysql-statis-v1.2.go
 * Description:
 */
package statis

/*import (
	"errors"
	"fmt"
	//"sort"
	//"strconv"
	//"strings"
	"time"

	log "github.com/cihub/seelog"
)*/

/*
   qtype-请求类型：
1-昨日数据
2-当日数据
3-总数据
4-洗衣点数据
5-洗衣机数据
*/

/*func (p *QKleagueStatis) GetQKLStatis(qtype int, userId string, extra map[string]interface{}) (error, []*StatisResp) {
	var resp []*StatisResp
	var err error
	switch qtype {
	case 1:
		yesterday := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
		err, resp = p.QKLSomeDay(userId, yesterday)
	case 2:
		today := time.Now().Format("2006-01-02")
		err, resp = p.QKLSomeDay(userId, today)
	case 3:
		err, resp = p.AllStatis(userId)
	case 4:
		err, resp = p.QKLWashRoomStatis(userId, extra)
	case 5:
		err, resp = p.QKLWasherStatis(extra)
	default:
	}
	return err, resp
}

func (p *QKleagueStatis) AllStatis(userId string) (error, []*StatisResp) {
	resp := make([]*StatisResp, 0, 1)
	sum := &StatisItem{}
	part := make([]*StatisItem, 0, 0)
	sum.Date = time.Now().Format("2006-01-02 15:04:05")

	sTick := int64(0)
	eTick := time.Now().Unix()
	sum.revenue, sum.pay, sum.TotalOrder = p.queryProfitOrders(sTick, eTick, "league_id", userId)
	sum.TotalRevenue = fmt.Sprintf("%.2f", float64(sum.revenue)/float64(100))
	sum.ActualPay = fmt.Sprintf("%.2f", float64(sum.pay)/float64(100))
	resp = append(resp, &StatisResp{sum, part})
	return nil, resp
}

func (p *QKleagueStatis) QKLSomeDay(userId, day string) (error, []*StatisResp) {
	resp := make([]*StatisResp, 0, 1)
	sum := &StatisItem{}
	part := make([]*StatisItem, 0, 0)
	sum.Date = time.Now().Format("2006-01-02 15:04:05")

	sTick, eTick := p.getSEtick(day, 1)
	sum.revenue, sum.pay, sum.TotalOrder = p.queryProfitOrders(sTick, eTick, "league_id", userId)

	sum.TotalRevenue = fmt.Sprintf("%.2f", float64(sum.revenue)/float64(100))
	sum.ActualPay = fmt.Sprintf("%.2f", float64(sum.pay)/float64(100))

	sum.WashedNum = p.queryUsedNum(sTick, eTick, "league_id", []string{userId})

	washerNum := p.getWasherNum(sTick, eTick, "league_id", []string{userId})

	if washerNum != 0 {
		sum.P1Machine = fmt.Sprintf("%.2f", float64(sum.revenue)/float64(washerNum*100))
		sum.O1Machine = fmt.Sprintf("%.2f", float64(sum.TotalOrder)/float64(washerNum))
	} else {
		sum.P1Machine = "0.00"
		sum.O1Machine = "0.00"
	}
	if sum.TotalOrder != 0 {
		sum.P1Order = fmt.Sprintf("%.2f", float64(sum.revenue)/float64(sum.TotalOrder*100))
	} else {
		sum.P1Order = "0.00"
	}

	resp = append(resp, &StatisResp{sum, part})
	return nil, resp
}

func (p *QKleagueStatis) QKLWashRoomStatis(userId string, extra map[string]interface{}) (error, []*StatisResp) {
	resp := make([]*StatisResp, 0)
	timeType := 0
	timeRange := ""
	if val, ok := extra["time_type"]; ok {
		timeType = int(val.(float64))
	}
	if val, ok := extra["time_range"]; ok {
		timeRange = val.(string)
	}
	if !p.isValidTimeRange(timeType, &timeRange) {
		log.Warnf("QKleagueStatis-WashRoomStatis, 时间范围不对; extra:%s", extra)
		return errors.New("invalid time_range"), nil
	}

	dates := p.calPeriodsByTstr(timeRange)
	if len(dates) == 0 {
		log.Errorf("QKLWashRoomStatis, calPeriodsByTstr, 时间范围不对; timeRange:%s", timeRange)
		return errors.New("invalid time_range"), nil
	}

	rooms := make([]string, 0)
	if val, ok := extra["rooms"]; ok {
		tmp := val.([]interface{})
		for _, dt := range tmp {
			rooms = append(rooms, dt.(string))
		}
	}

	for _, date := range dates {
		data := p.QKLWashRoomSomePeriodStatis(rooms, userId, date, timeType)
		resp = append(resp, data)
	}
	return nil, resp
}

func (p *QKleagueStatis) QKLWasherStatis(extra map[string]interface{}) (error, []*StatisResp) {
	resp := make([]*StatisResp, 0)
	if extra == nil {
		return errors.New("invalid param extra"), nil
	}
	timeType := 0
	timeRange := ""
	if val, ok := extra["time_type"]; ok {
		timeType = int(val.(float64))
	}
	if val, ok := extra["time_range"]; ok {
		timeRange = val.(string)
	}
	if !p.isValidTimeRange(timeType, &timeRange) {
		log.Warnf("QKLWasherStatis, 时间范围不对; extra:%s", extra)
		return errors.New("invalid time_range"), nil
	}

	rooms := make([]string, 0)
	if val, ok := extra["rooms"]; ok {
		tmp := val.([]interface{})
		for _, dt := range tmp {
			rooms = append(rooms, dt.(string))
		}
	}

	pWashers := make([]string, 0)
	if val, ok := extra["washers"]; ok {
		tmp := val.([]interface{})
		for _, dt := range tmp {
			pWashers = append(pWashers, dt.(string))
		}
	}

	dates := p.calPeriodsByTstr(timeRange)
	if len(dates) == 0 {
		log.Errorf("QKLWasherStatis, calPeriodsByTstr, 时间范围不对; timeRange:%s", timeRange)
		return errors.New("invalid time_range"), nil
	}

	washers := make([]string, 0)
	if len(pWashers) != 0 {
		washers = append(washers, pWashers...)
	} else {
		sTick, _ := p.getSEtick(dates[len(dates)-1], timeType)
		_, eTick := p.getSEtick(dates[0], timeType)
		for _, roomId := range rooms {
			ws := p.getRoomWashers(sTick, eTick, roomId)
			washers = append(washers, ws...)
			washers = p.delSameItem(washers)
		}
	}

	for _, washerId := range washers {
		data := p.QKLWasherSomePeriodStatis(washerId, dates, timeType)
		resp = append(resp, data)
	}
	return nil, resp
}

//洗衣房集合的某个时间段的数据
func (p *QKleagueStatis) QKLWashRoomSomePeriodStatis(prooms []string, userId, period string, dtype int) *StatisResp {
	//dtype 1-日数据 2-月数据
	//period 获取时间范围
	var sTick, eTick int64
	switch dtype {
	case 1:
		sTick, eTick = p.getSEtick(period, 1)
	case 2:
		sTick, eTick = p.getSEtick(period, 2)
	}

	sum := &StatisItem{}
	part := make([]*StatisItem, 0, 0)
	sum.Date = period

	roomList := make(map[string]*StatisItem)

	rooms := make([]string, 0)
	if len(prooms) == 0 {
		//没有指定洗衣点,动态获取洗衣点集合
		sTick, eTick := p.getSEtick(period, dtype)
		rooms = p.getLeagueRooms(sTick, eTick, userId)
	} else {
		rooms = append(rooms, prooms...)
	}
	//获取洗衣点的营收数居
	for _, roomId := range rooms {
		wsTick, weTick := p.getWashRoomSETick(roomId) //洗衣点测创建时间和截止时间
		if sTick >= weTick || eTick <= wsTick {
			continue
		}

		if _, ok := roomList[roomId]; !ok {
			roomList[roomId] = &StatisItem{}
		}
		roomList[roomId].Date = period
		roomList[roomId].StatisId = roomId

		roomList[roomId].revenue, roomList[roomId].pay, roomList[roomId].TotalOrder = p.queryProfitOrders(sTick, eTick, "room_id", roomId)

		roomList[roomId].WashedNum = p.queryUsedNum(sTick, eTick, "room_id", []string{roomId})

		//获取洗衣房名称，需要改变
		roomList[roomId].StatisTDesc = p.getWashRoomName(roomId)

		roomList[roomId].ActualPay = fmt.Sprintf("%.2f", float64(roomList[roomId].pay)/float64(100))
		roomList[roomId].TotalRevenue = fmt.Sprintf("%.2f", float64(roomList[roomId].revenue)/float64(100))

		sum.revenue += roomList[roomId].revenue
		sum.pay += roomList[roomId].pay
		sum.TotalOrder += roomList[roomId].TotalOrder

		washerNum := p.getWasherNum(sTick, eTick, "room_id", []string{roomId})
		if washerNum != 0 {
			roomList[roomId].P1Machine = fmt.Sprintf("%.2f", float64(roomList[roomId].revenue)/float64(washerNum*100))
			roomList[roomId].O1Machine = fmt.Sprintf("%.2f", float64(roomList[roomId].TotalOrder)/float64(washerNum))
		} else {
			roomList[roomId].P1Machine = "0.00"
			roomList[roomId].O1Machine = "0.00"
		}

		if roomList[roomId].TotalOrder != 0 {
			roomList[roomId].P1Order = fmt.Sprintf("%.2f", float64(roomList[roomId].revenue)/float64(roomList[roomId].TotalOrder*100))
		} else {
			roomList[roomId].P1Order = "0.00"
		}

		part = append(part, roomList[roomId])
	}
	sum.TotalRevenue = fmt.Sprintf("%.2f", float64(sum.revenue)/float64(100))
	sum.ActualPay = fmt.Sprintf("%.2f", float64(sum.pay)/float64(100))

	allWasherNum := p.getWasherNum(sTick, eTick, "room_id", rooms)
	if allWasherNum != 0 {
		sum.P1Machine = fmt.Sprintf("%.2f", float64(sum.revenue)/float64(allWasherNum*100))
		sum.O1Machine = fmt.Sprintf("%.2f", float64(sum.TotalOrder)/float64(allWasherNum))
	} else {
		sum.P1Machine = "0.00"
		sum.O1Machine = "0.00"
	}

	if sum.TotalOrder != 0 {
		sum.P1Order = fmt.Sprintf("%.2f", float64(sum.revenue)/float64(sum.TotalOrder*100))
	} else {
		sum.P1Order = "0.00"
	}

	sum.WashedNum = p.queryUsedNum(sTick, eTick, "room_id", rooms)

	resp := &StatisResp{sum, part}
	return resp
}

//一个时间集合洗衣机数据 时间从大到小排序
func (p *QKleagueStatis) QKLWasherSomePeriodStatis(washerId string, periods []string, dtype int) *StatisResp {
	sum := &StatisItem{}
	sum.StatisId = washerId
	part := make([]*StatisItem, 0, 0)
	sum.Date = fmt.Sprintf("%s~%s", periods[len(periods)-1], periods[0])
	sum.StatisId = washerId

	periodList := make(map[string]*StatisItem)

	var sTick, eTick int64
	wsTick, weTick := p.getWasherSETick(washerId) //洗衣机测创建时间和截止时间
	//fmt.Printf("wsTick:%d, weTick:%d\n", wsTick, weTick)
	for _, period := range periods {
		sTick, eTick = p.getSEtick(period, dtype)
		//	fmt.Printf("sTick:%d, eTick:%d\n", sTick, eTick)

		if sTick >= weTick || eTick <= wsTick {
			continue
		}

		if _, ok := periodList[washerId]; !ok {
			periodList[period] = &StatisItem{}
			periodList[period].StatisId = washerId
		}

		periodList[period].StatisId = washerId
		periodList[period].StatisTDesc = p.getWasherAddr(sTick, eTick, washerId)

		periodList[period].Date = period

		periodList[period].revenue, periodList[period].pay, periodList[period].TotalOrder = p.queryProfitOrders(sTick, eTick, "washer_id", washerId)

		periodList[period].WashedNum = p.queryUsedNum(sTick, eTick, "washer_id", []string{washerId})

		periodList[period].TotalRevenue = fmt.Sprintf("%.2f", float64(periodList[period].revenue/100))
		periodList[period].ActualPay = fmt.Sprintf("%.2f", float64(periodList[period].pay/100))

		if periodList[period].TotalOrder != 0 {
			periodList[period].P1Order = fmt.Sprintf("%.2f", float64(periodList[period].revenue)/float64(periodList[period].TotalOrder*100))
		} else {
			periodList[period].P1Order = "0.00"
		}
		part = append(part, periodList[period])

		sum.revenue += periodList[period].revenue
		sum.pay += periodList[period].pay
		sum.TotalOrder = periodList[period].TotalOrder

	}
	sum.TotalRevenue = fmt.Sprintf("%.2f", float64(sum.revenue)/float64(100))
	sum.ActualPay = fmt.Sprintf("%.2f", float64(sum.pay)/float64(100))

	if sum.TotalOrder != 0 {
		sum.P1Order = fmt.Sprintf("%.2f", float64(sum.revenue)/float64(sum.TotalOrder*100))
	} else {
		sum.P1Order = "0.00"
	}

	sTick, _ = p.getSEtick(periods[len(periods)-1], dtype)
	_, eTick = p.getSEtick(periods[0], dtype)
	sum.WashedNum = p.queryUsedNum(sTick, eTick, "washer_id", []string{washerId})

	resp := &StatisResp{sum, part}
	return resp
}*/
